package com.bruce.asurada.sso.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;

/**
 * 数据库连接测试
 * 
 * @author Bruce
 */
@Slf4j
@Component
public class DatabaseConnectionTest implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        testMysqlConnection();
        testRedisConnection();
    }

    /**
     * 测试MySQL连接
     */
    private void testMysqlConnection() {
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                log.info("✅ MySQL数据库连接成功！");
                log.info("数据库URL: {}", connection.getMetaData().getURL());
                log.info("数据库驱动: {}", connection.getMetaData().getDriverName());
                log.info("数据库版本: {}", connection.getMetaData().getDatabaseProductVersion());
            }
        } catch (Exception e) {
            log.error("❌ MySQL数据库连接失败: {}", e.getMessage());
            log.error("请检查以下配置:");
            log.error("1. MySQL服务是否启动");
            log.error("2. 数据库连接配置是否正确");
            log.error("3. 数据库用户名密码是否正确");
            log.error("4. 数据库 asurada_sso_db 是否已创建");
        }
    }

    /**
     * 测试Redis连接
     */
    private void testRedisConnection() {
        try {
            // 测试Redis连接
            redisTemplate.opsForValue().set("connection_test", "test_value");
            String testValue = (String) redisTemplate.opsForValue().get("connection_test");
            
            if ("test_value".equals(testValue)) {
                log.info("✅ Redis连接成功！");
                
                // 获取Redis信息
                String info = redisTemplate.getConnectionFactory()
                    .getConnection()
                    .serverCommands()
                    .info("server")
                    .getProperty("redis_version");
                
                log.info("Redis版本: {}", info);
                
                // 清理测试数据
                redisTemplate.delete("connection_test");
            }
        } catch (Exception e) {
            log.error("❌ Redis连接失败: {}", e.getMessage());
            log.error("请检查以下配置:");
            log.error("1. Redis服务是否启动");
            log.error("2. Redis连接配置是否正确");
            log.error("3. Redis密码配置是否正确");
            log.error("4. Redis端口是否可访问");
        }
    }
}